import {
  reqAddHospitalSet,
  reqGetHospitalSetById,
  reqUpdateHospitalSet,
} from "@/api/hospital/hospitalSet";
import { ReqAddHospitalSetParams } from "@/api/hospital/hospitalSet/types";
import { Button, Card, Form, Input, Space, message } from "antd";
import React, { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";

export default function AddOrUpdateHospital() {
  //获取列表传递过来的 id 参数
  let { id } = useParams();
  //获取 form 对象
  let [form] = Form.useForm();

  //获得 navigate 函数
  let navigate = useNavigate();

  //声明 onFinish 函数
  let onFinish = async (values: ReqAddHospitalSetParams) => {
    if (!id) {
      //发送请求 新增医院
      await reqAddHospitalSet(values);
    }else{
      //更新流程
      await reqUpdateHospitalSet({
        ...values,
        id
      });
    }
    //操作提醒
    message.success(`${id ? '更新' : '新增'}成功`);
    navigate("/syt/hospital/hospitalSet");
  };

  //返回
  let back = () => {
    navigate(-1);
  };

  //定义 useEffect 回调
  useEffect(() => {
    //判断
    if(!id) return;
    //定义一个函数
    let getData = async () => {
      //调用函数发送 AJAX 请求
      let result = await reqGetHospitalSetById(id as string);
      //修改表单元素的值
      form.setFieldsValue(result);
    };
    getData();
  }, []);

  return (
    <Card>
      <Form
        form={form}
        name="basic"
        labelCol={{ span: 2 }}
        wrapperCol={{ span: 22 }}
        onFinish={onFinish}
        autoComplete="off"
      >
        <Form.Item
          label="医院名称"
          name="hosname"
          rules={[{ required: true, message: "医院名称不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="医院编号"
          name="hoscode"
          rules={[{ required: true, message: "医院编号不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="API路径"
          name="apiUrl"
          rules={[{ required: true, message: "API路径不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人姓名"
          name="contactsName"
          rules={[{ required: true, message: "联系人姓名不能为空" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="联系人手机"
          name="contactsPhone"
          rules={[
            { required: true, message: "手机号不能为空" },
            { pattern: /^1[3-9]\d{9}$/, message: "手机号格式不正确" },
          ]}
        >
          <Input />
        </Form.Item>

        <Form.Item wrapperCol={{ offset: 2, span: 16 }}>
          <Space>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
            <Button onClick={back}>返回</Button>
          </Space>
        </Form.Item>
      </Form>
    </Card>
  );
}
